import { useAppStoreWithOut } from '@/store';
import { deepCopy, getSessionStorage } from '@/core/utils/util';
import { Http } from './http';
import { getCookie } from 'qx-util';
import { i18n } from '@/locales';
import { HttpResponse, ILoadingHelper, IParam } from '@/core';
import { AxiosResponse } from 'axios';

/**
 * 拦截器
 *
 * @export
 * @class Interceptors
 */
export class Interceptors {
	/**
	 * 路由对象
	 *
	 * @private
	 * @type {(Router | any)}
	 * @memberof Interceptors
	 */
	private router: any;

	/**
	 *  单列对象
	 *
	 * @private
	 * @static
	 * @type { Interceptors }
	 * @memberof Interceptors
	 */
	private static instance: Interceptors;

	/**
	 * 应用加载助手
	 *
	 * @private
	 * @type {ILoadingHelper}
	 * @memberof Interceptors
	 */
	private readonly appLoadingHelper!: ILoadingHelper;

	/**
	 * Creates an instance of Interceptors.
	 * 私有构造，拒绝通过 new 创建对象
	 *
	 * @memberof Interceptors
	 */
	private constructor(router: any) {
		this.router = router;
		this.appLoadingHelper = App.getAppLoadingHelper();
		this.intercept();
	}

	/**
	 * 获取 Interceptors 单例对象
	 *
	 * @static
	 * @param {Router} route
	 * @param {Store<any>} store
	 * @returns {Interceptors}
	 * @memberof Interceptors
	 */
	public static getInstance(router: any): Interceptors {
		if (!this.instance) {
			this.instance = new Interceptors(router);
		}
		return this.instance;
	}

	/**
	 * 拦截器实现接口
	 *
	 * @private
	 * @memberof Interceptors
	 */
	private intercept(): void {
		Http.getHttp().interceptors.request.use(
			(config: any) => {
				const { getAppData: appData } = useAppStoreWithOut();
				if (appData && appData.context) {
					config.headers['srforgsectorid'] = appData.context.srforgsectorid;
				}
				const projectSetting = App.getProjectSetting();
                const localData = localStorage.getItem('activeOrgData');
                const activeOrgData = getSessionStorage('activeOrgData');
                if(localData){
					const localItem = JSON.parse(localData);
                    config.headers['srforgid'] = localItem.organization_id;
                    config.headers['srforgsectorid'] = localItem.department_id;
                    if (localItem.system_id) {
                        config.headers['srfsystemid'] = localItem.system_id;
                    }
                    if (localItem.deploy_system_id) {
                        config.headers['srfdcsystemid'] = localItem.deploy_system_id;
                    }
                } else if (activeOrgData) {
                    config.headers['srforgid'] = activeOrgData.organization_id;
                    config.headers['srforgsectorid'] = activeOrgData.department_id;
                    if (activeOrgData.system_id) {
                        config.headers['srfsystemid'] = activeOrgData.system_id;
                    }
                    if (activeOrgData.deploy_system_id) {
                        config.headers['srfdcsystemid'] = activeOrgData.deploy_system_id;
                    }
                }
				if (getCookie('ibzuaa-token')) {
					config.headers['Authorization'] = `Bearer ${getCookie(
						'ibzuaa-token'
					)}`;
				} else {
					// 第三方应用打开免登
					if (sessionStorage.getItem('srftoken')) {
						const token = sessionStorage.getItem('srftoken');
						config.headers['Authorization'] = `Bearer ${token}`;
					}
				}
				config.headers['Accept-Language'] = i18n.global.locale.value;
				if (
					!config.url.startsWith('https://') &&
					!config.url.startsWith('http://')
				) {
					this.handleRequest(config);
				}
				// 开启loading
				this.beginLoading();
				return config;
			},
			(error: any) => {
				return Promise.reject(error);
			}
		);

		Http.getHttp().interceptors.response.use(
			(response: AxiosResponse) => {
                // TODO 适配安永接口
				// this.handleResponse(response);
				// 关闭loading
				this.endLoading();
				if (response.status === 401) {
					App.login();
				}
				if (response.status === 404) {
					// this.router.push({ path: '/404' });
				} else if (response.status === 500) {
					// this.router.push({ path: '/500' });
				}
				return new HttpResponse(response.data, response);
			},
			(error: any) => {
				// 关闭loading
				this.endLoading();
				error = error ? error : { response: {} };
				const { response: res } = error;
				const { data: _data } = res;
				// 处理异常
				if (res.headers && res.headers['x-ibz-error']) {
					res.data.errorKey = res.headers['x-ibz-error'];
				}
				if (res.headers && res.headers['x-ibz-params']) {
					res.data.entityName = res.headers['x-ibz-params'];
				}
				if (res.status === 401) {
					App.login();
				}
				if (res.status === 404) {
					// this.router.push({ path: '/404' });
				} else if (res.status === 500) {
					// this.router.push({ path: '/500' });
				}
				return new HttpResponse(res.data, res);
			}
		);
	}

	/**
	 * 请求之前处理
	 *
	 * @param {*} config
	 * @param {*} config
	 * @memberof Interceptors
	 */
	private handleRequest(config: any) {
		if (config.data) {
			try {
				const handle = (data: IParam = {}) => {
					if (data && data.$DO) {
						delete data.$DO;
					}
				};
				const data = JSON.parse(JSON.stringify(config.data));
				if (!data) {
					return;
				}
				if (Object.prototype.toString.call(data) === '[object Object]') {
					handle(data);
				}
				if (Object.prototype.toString.call(data) === '[object Array]') {
					data.forEach((d: IParam) => {
						handle(d);
					});
				}
				config.data = data;
			} catch (error) {
				throw error;
			}
		}
		const requestUrl = config.url;
		const projectSetting = App.getProjectSetting();
		// 是否启用远端模式
		if (projectSetting.enableRemoteMode) {
			// 核心服务
			if (
				// uaa
				requestUrl.startsWith(`/v7`) ||
				requestUrl.startsWith(`/uaa`) ||
				requestUrl.startsWith(`/sysauthlogs`) ||
				// ou
				requestUrl.startsWith(`/ibzemployees`) ||
				requestUrl.startsWith(`/ibzemployees`) ||
				requestUrl.startsWith(`/ibzdepartments`) ||
				requestUrl.startsWith(`/sysdepartments`) ||
				requestUrl.startsWith(`/ibzorganizations`) ||
				requestUrl.startsWith(`/sysorganizations`) ||
				// oss
				requestUrl.startsWith(`/ibizutil`) ||
				requestUrl.startsWith(`/net-disk`) ||
				// configs
				requestUrl.startsWith(`/configs`) ||
				// dict
				requestUrl.startsWith(`/dictionar`) ||
				// wfcore
				requestUrl.startsWith(`/wfcore`)
			) {
				const serviceUrlMap: any = projectSetting.serviceUrlMap;
				const targetKey = Object.keys(serviceUrlMap).find((key: any) => {
					return config.url.startsWith(key);
				});
				// 存在核心服务映射处理直达路径
				if (targetKey) {
					config.url = serviceUrlMap[targetKey] + config.url;
				} else {
					if (!Object.is(import.meta.env.VITE_BASE_URL, '')) {
						config.url = import.meta.env.VITE_BASE_URL + config.url;
					}
				}
			} else {
				// 业务服务
				config.url = projectSetting.businessServiceUrl + config.url;
			}
		} else {
			if (!Object.is(import.meta.env.VITE_BASE_URL, '')) {
				config.url = import.meta.env.VITE_BASE_URL + config.url;
			}
		}
	}

	/**
	 * 处理响应
	 *
	 * @private
	 * @param {*} response
	 * @memberof Interceptors
	 */
	private handleResponse(response: any) {
		const requestUrl = response.config.url;
		// 请求基础路径
		const projectSetting = App.getProjectSetting();
		let baseRequestUrl = import.meta.env.VITE_BASE_URL;
		// 是否启用远端模式
		if (projectSetting.enableRemoteMode) {
			const serviceUrlMap: any = projectSetting.serviceUrlMap;
			let targetValue: string | undefined = Object.values(serviceUrlMap).find(
				(value: any) => {
					return requestUrl.startsWith(value);
				}
			) as unknown as string | undefined;
			if (targetValue) {
				baseRequestUrl = targetValue;
			}
		}
		// 静态资源
		if (
			// uaa
			requestUrl.startsWith(`${baseRequestUrl}/v7`) ||
			requestUrl.startsWith(`${baseRequestUrl}/uaa`) ||
			requestUrl.startsWith(`${baseRequestUrl}/sysauthlogs`) ||
			// ou
			requestUrl.startsWith(`${baseRequestUrl}/ibzemployees`) ||
			requestUrl.startsWith(`${baseRequestUrl}/ibzemployees`) ||
			requestUrl.startsWith(`${baseRequestUrl}/ibzdepartments`) ||
			requestUrl.startsWith(`${baseRequestUrl}/sysdepartments`) ||
			requestUrl.startsWith(`${baseRequestUrl}/ibzorganizations`) ||
			requestUrl.startsWith(`${baseRequestUrl}/sysorganizations`) ||
			// oss
			requestUrl.startsWith(`${baseRequestUrl}/ibizutil`) ||
			requestUrl.startsWith(`${baseRequestUrl}/net-disk`) ||
			// configs
			requestUrl.startsWith(`${baseRequestUrl}/configs`) ||
			// dict
			requestUrl.startsWith(`${baseRequestUrl}/dictionar`) ||
			// wfcore
			requestUrl.startsWith(`${baseRequestUrl}/wfcore`)
		) {
			return response;
		} else {
			const responseData = deepCopy(response.data);
			if (responseData.hasOwnProperty('code')) {
				response.status =
					responseData.code === '200' ? 200 : Number(responseData.code);
			}
			// 成功
			if (responseData.success) {
				if (responseData.hasOwnProperty('result')) {
					const result = responseData.result;
					// 分页结果
					if (responseData.pageResult) {
						response.data = result.list;
						if (result.hasOwnProperty('total')) {
							Object.assign(response, { total: Number(result.total) });
						}
						const config = response.config;
						if (config && config.data) {
							const data = JSON.parse(config.data);
							if (data && data.hasOwnProperty('page')) {
								Object.assign(response, { page: Number(data.page) });
							}
							if (data && data.hasOwnProperty('size')) {
								Object.assign(response, { size: Number(data.size) });
							}
						}
					} else {
						if (
							result &&
							Object.prototype.toString.call(result) === '[object Object]'
						) {
							response.data = result;
						} else {
							response.data = result;
						}
					}
				}
			} else {
				// 失败
				if (responseData.hasOwnProperty('message') && responseData.message) {
					response.message = responseData.message;
				}
			}
		}
	}

	/**
	 * 开始加载
	 *
	 * @private
	 * @memberof Http
	 */
	private beginLoading(): void {
		this.appLoadingHelper.beginLoading();
	}

	/**
	 * 加载结束
	 *
	 * @private
	 * @memberof Http
	 */
	private endLoading(): void {
		this.appLoadingHelper.endLoading();
	}
}
